<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <div style="font-size: 16px; margin-top: 5px">组装后产品</div>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          v-if="optType !== 'view'"
          @click="handleSelectItem"
          v-hasPermi="['wm:assembly:add']"
        >选择</el-button>
      </el-col>
      <el-col :span="1.5">
        <div style="font-size: 12px; margin-top: 5px;color: red">只能添加一条数据</div>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wm:assemblyline:edit']"
        >修改</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
<!--组装后     就一条数据不需要分页   -->
    <el-table v-loading="loading" :data="assemblylineList" @selection-change="handleSelectionChange" border>
      <el-table-column type="index" label="序号" width="55" align="center"/>
      <el-table-column label="产品编码" align="center" prop="itemCode" />
      <el-table-column label="产品名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="批次号" align="center" prop="batchCode" width="300">
        <template slot-scope="scope" >
          <div style="display: flex; align-items: center; gap: 8px">
            <el-input v-model="scope.row.batchCode" :disabled="scope.row.enableBatchFlag !=='Y' || optType =='view'"  placeholder="批次号" />
            <el-switch
              v-if ="scope.row.enableBatchFlag =='Y'"
              v-model="scope.row.autoGenCodeFlag"
              active-color="#13ce66"
              active-text="自动生成"
              @change="handleLineAutoGenCode(scope.row.autoGenCodeFlag,scope.row)"
            >
            </el-switch>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="lineQuantity" >
        <template slot-scope="scope">
          <el-input-number :min="0" :max="99999999999" :disabled="optType =='view'" controls-position="right"
               size="mini" style="width:120px" v-model="scope.row.lineQuantity"  @change="handleChangeZhu(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="辅单位" align="center" prop="storageUnit" />
      <el-table-column label="辅数量" align="center" prop="storageUnitQuantity" >
        <template slot-scope="scope">
          <el-input-number :min="0" :max="99999999999" :disabled="optType =='view' || 'N' == scope.row.enableMultiUnit " controls-position="right"
                           size="mini" style="width:120px" v-model="scope.row.storageUnitQuantity"  @change="handleChangeZhu(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="BOM" align="center" prop="bomId" width="150px">
        <template slot-scope="scope">
          <el-select v-model="scope.row.bomId" placeholder="请选择BOM"  :disabled="optType =='view'"
                     @change="handleBomChange($event,scope.row)"
                     @visible-change="handleBomVisibleChange(($event,scope.row))"
                     v-loading="bomSelectLoading">
            <el-option
                v-for="item in bomList"
                :key="item.bomId"
                :label="`${item.bomCode}-${item.bomName}`"
                :value="item.bomId">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="材料单价" align="center" prop="materialPrice" />
      <el-table-column label="材料金额" align="center" prop="materialAmount" />
      <el-table-column label="费用" align="center" prop="productCost" >
        <template slot-scope="scope">
          <el-input-number :min="0" :max="99999999999" :disabled="optType =='view'" controls-position="right"
                           :percision="2"  size="mini" style="width:120px"  v-model="scope.row.productCost"  @change="handleChangeCost(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="金额" align="center" prop="billAmount" />
      <el-table-column label="图号" align="center" prop="drawNumber" />
<!--      <el-table-column label="仓库ID" align="center" prop="warehouseId" />
      <el-table-column label="仓库编码" align="center" prop="warehouseCode" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="库区ID" align="center" prop="locationId" />
      <el-table-column label="库区编码" align="center" prop="locationCode" />
      <el-table-column label="库区名称" align="center" prop="locationName" />
      <el-table-column label="库位ID" align="center" prop="areaId" />
      <el-table-column label="库位编码" align="center" prop="areaCode" />
      <el-table-column label="库位名称" align="center" prop="areaName" />-->
      <el-table-column label="仓库" align="center" prop="warehouseId" width="150px">
        <template slot-scope="scope">
                  <el-select v-model="scope.row.warehouseId" placeholder="请选择库区" :disabled="optType =='view'"
                             @change="handleToWarehouseChange($event,scope.row)" >
                    <el-option
                      v-for="item in toWarehouseList"
                      :key="item.warehouseId"
                      :label="item.warehouseName"
                      :value="item.warehouseId">
                    </el-option>
                  </el-select>
          </template>
      </el-table-column>
      <el-table-column label="库区" width="150px" align="center" prop="locationId">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.locationId" placeholder="请选择库区" :disabled="optType =='view'"
                             @change="handleLocationChange($event,scope.row)"
                             @visible-change="handleToLocationVisibleChange(($event,scope.row))"
                             v-loading="locationSelectLoading"
                            >
                    <el-option
                      v-for="item in locationList"
                      :key="item.locationId"
                      :label="item.locationName"
                      :value="item.locationId">
                    </el-option>
                  </el-select>
                </template>
      </el-table-column>
      <el-table-column label="库位" align="center" prop="areaId" width="120px">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.areaId" placeholder="请选择库位" :disabled="optType =='view'"
                             @change="handleAreaChange($event,scope.row)"
                             @visible-change="handleVisibleChange(($event,scope.row))"
                             v-loading="areaSelectLoading">
                    <el-option
                      v-for="item in areaList"
                      :key="item.areaId"
                      :label="item.areaName"
                      :value="item.areaId">
                    </el-option>
                  </el-select>
                </template>
      </el-table-column>
      <el-table-column label="辅单位" align="center" prop="storageUnit" />
      <el-table-column label="辅换算方式" align="center" prop="storageUnitType" >
        <template slot-scope="scope">
          <span v-if="scope.row.storageUnitType === 'fixed'"  >固定</span>
          <span v-if="scope.row.storageUnitType === 'float'"  >浮动</span>
        </template>
      </el-table-column>
      <el-table-column label="辅换算比例" align="center" prop="storageRatio" />


<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="optType !== 'view'">
        <template slot-scope="scope">
&lt;!&ndash;          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wm:assemblyline:edit']"
          >修改</el-button>&ndash;&gt;
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row, scope.$index)"
            v-hasPermi="['wm:assembly:remove']"
          >删除</el-button>
        </template>
      </el-table-column>-->
    </el-table>
    </el-card>
<!--    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />-->
<!--=======================================================组装前============================================================================================================================-->
    <div style="height: 30px"></div>
    <el-card style="border-radius: 10px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <div style="font-size: 16px; margin-top: 5px">组装前物料</div>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            v-if="optType !== 'view'"
            @click="handleAutoStock"
            v-hasPermi="['wm:assembly:add']"
        >自动匹配库存</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <div style="font-size: 12px; margin-top: 5px;color: #a7e0ed">蓝色正常；绿色数量不够，但已是所有库存量；红色没有库存</div>
      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>
    <el-table v-loading="loading" :data="beforeLineList" @selection-change="handleSelectionChange"   show-summary
              :summary-method="getSummaries"  border>
      <el-table-column type="index" label="序号" width="55" align="center"/>
      <el-table-column label="产品编码" align="center" prop="itemCode" />
      <el-table-column label="产品名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="数量" align="center" prop="lineQuantity" >
        <template slot-scope="scope">
          <el-tag
            :type="getQuantityTagType(scope.row)"
            size="small"
          >
            {{ scope.row.lineQuantity }}

          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="图号" align="center" prop="drawNumber" />
      <el-table-column label="批次号" align="center" prop="batchCode" />
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="金额" align="center" prop="billAmount" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="库区名称" align="center" prop="locationName" />
      <el-table-column label="库位名称" align="center" prop="areaName" />
      <el-table-column label="辅单位" align="center" prop="storageUnit" />
      <el-table-column label="辅换算方式" align="center" prop="storageUnitType" >
        <template slot-scope="scope">
          <span v-if="scope.row.storageUnitType === 'fixed'"  >固定</span>
          <span v-if="scope.row.storageUnitType === 'float'"  >浮动</span>
        </template>
      </el-table-column>
      <el-table-column label="辅换算比例" align="center" prop="storageRatio" />
      <el-table-column label="辅单位数量" align="center" prop="storageUnitQuantity" >
        <template slot-scope="scope">
          <el-input-number :min="0" :max="99999999999" :disabled="optType =='view' || 'N' == scope.row.enableMultiUnit "
                           controls-position="right"
                           size="mini" style="width:100px" v-model="scope.row.storageUnitQuantity"  @change="handleChangeZhu(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>

<!--      <el-table-column label="是否启用多单位" align="center" prop="enableMultiUnit" />-->

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  v-if="optType !== 'view'">
        <template slot-scope="scope">
<!--          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wm:assemblyline:edit']"
          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeleteBeforeLine(scope.row, scope.$index)"
            v-hasPermi="['wm:assembly:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

<!--    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />-->
    </el-card>
    <ItemSelect ref="itemSelect" @onSelected="onItemSelected"></ItemSelect>

    <!-- 添加或修改组装单行对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物料id" prop="itemId">
          <el-input v-model="form.itemId" placeholder="请输入物料id" />
        </el-form-item>
        <el-form-item label="物料编码" prop="itemCode">
          <el-input v-model="form.itemCode" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="物料名称" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="规格型号" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="单位" prop="unitOfMeasure">
          <el-input v-model="form.unitOfMeasure" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="数量" prop="lineQuantity">
          <el-input v-model="form.lineQuantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="材料单价" prop="materialPrice">
          <el-input v-model="form.materialPrice" placeholder="请输入材料单价" />
        </el-form-item>
        <el-form-item label="材料金额" prop="materialAmount">
          <el-input v-model="form.materialAmount" placeholder="请输入材料金额" />
        </el-form-item>
        <el-form-item label="费用" prop="productCost">
          <el-input v-model="form.productCost" placeholder="请输入费用" />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="金额" prop="billAmount">
          <el-input v-model="form.billAmount" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="仓库ID" prop="warehouseId">
          <el-input v-model="form.warehouseId" placeholder="请输入仓库ID" />
        </el-form-item>
        <el-form-item label="仓库编码" prop="warehouseCode">
          <el-input v-model="form.warehouseCode" placeholder="请输入仓库编码" />
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="库区ID" prop="locationId">
          <el-input v-model="form.locationId" placeholder="请输入库区ID" />
        </el-form-item>
        <el-form-item label="库区编码" prop="locationCode">
          <el-input v-model="form.locationCode" placeholder="请输入库区编码" />
        </el-form-item>
        <el-form-item label="库区名称" prop="locationName">
          <el-input v-model="form.locationName" placeholder="请输入库区名称" />
        </el-form-item>
        <el-form-item label="库位ID" prop="areaId">
          <el-input v-model="form.areaId" placeholder="请输入库位ID" />
        </el-form-item>
        <el-form-item label="库位编码" prop="areaCode">
          <el-input v-model="form.areaCode" placeholder="请输入库位编码" />
        </el-form-item>
        <el-form-item label="库位名称" prop="areaName">
          <el-input v-model="form.areaName" placeholder="请输入库位名称" />
        </el-form-item>
        <el-form-item label="辅单位" prop="storageUnit">
          <el-input v-model="form.storageUnit" placeholder="请输入辅单位" />
        </el-form-item>
        <el-form-item label="辅换算方式" prop="storageUnitType">
          <el-select v-model="form.storageUnitType" placeholder="请选择辅换算方式">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="辅换算比例" prop="storageRatio">
          <el-input v-model="form.storageRatio" placeholder="请输入辅换算比例" />
        </el-form-item>
        <el-form-item label="辅单位数量" prop="storageUnitQuantity">
          <el-input v-model="form.storageUnitQuantity" placeholder="请输入辅单位数量" />
        </el-form-item>
        <el-form-item label="是否启用多单位" prop="enableMultiUnit">
          <el-input v-model="form.enableMultiUnit" placeholder="请输入是否启用多单位" />
        </el-form-item>
        <el-form-item label="物料bom" prop="bomId">
          <el-input v-model="form.bomId" placeholder="请输入物料bom" />
        </el-form-item>
        <el-form-item label="bom版本" prop="bomName">
          <el-input v-model="form.bomName" placeholder="请输入bom版本" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getBomList} from "@/api/mes/md/bomgl";
import { listAssemblyline,getListAssemblyline, getAssemblyline,getLineInfo,delAssemblyline, addAssemblyline, updateAssemblyline,getBomItemStock } from "@/api/mes/wm/assemblyline";
import Template from "@/views/print/printtemplate/list.vue";
import ItemSelect from "@/components/itemSelect/single.vue";
import {getWarehouseList} from "@/api/mes/wm/warehouse";
import {getLocationList} from "@/api/mes/wm/location";
import {getAreaList} from "@/api/mes/wm/area";
import {genCode} from "@/api/system/autocode/rule";

export default {
  name: "Assemblyline",
  components: {ItemSelect, Template},
  props: {
    assemblyId:null,
    optType: null,
    beforsWarehouseIds:null
  },
  data() {
    return {
      bomList:[],
      bomSelectLoading:false,
      areaSelectLoading:false,
      locationSelectLoading:false,
      //仓库
      toWarehouseList:[],
      //库区
      locationList:[],
      //库位
      areaList:[],

      insufficientItems:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 组装单行表格数据
      assemblylineList: [],
      beforeLineList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assemblyId:this.assemblyId,
        itemId: null,        itemCode: null,        itemName: null,
        specification: null,        unitOfMeasure: null,        lineQuantity: null,
        materialPrice: null,        materialAmount: null,        productCost: null,
        price: null,        billAmount: null,
        warehouseId: null,        warehouseCode: null,        warehouseName: null,
        locationId: null,        locationCode: null,        locationName: null,
        areaId: null,        areaCode: null,        areaName: null,
        storageUnit: null,        storageUnitType: null,        storageRatio: null,
        storageUnitQuantity: null,        enableMultiUnit: null,
        bomId: null,        bomName: null,        createByName: null   },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getWarehouse()
  },
  methods: {
    /** 查询组装单行列表 */
    getList() {
      this.assemblylineList=[]
      this.beforeLineList=[]
      if(this.assemblyId){
        this.loading = true;
        getLineInfo(this.assemblyId).then(response => {
          // this.assemblylineList = response.rows;
          this.assemblylineList = response.data.filter(item => item.lineType === 'after_line');
          this.beforeLineList = response.data.filter(item => item.lineType === 'before_line');
          // this.total = response.total;
          // 用于显示bom 下拉列表    assemblylineList中就一条数据
          this.bomList=[]
          getBomList({ancestors: '0',status:'发布',itemId: this.assemblylineList[0].itemId}).then(response =>{
            this.bomList=response.data
            this.bomSelectLoading=false
          })
          this.loading = false;
        });
      }else{
        this.loading = false;
      }

    },
    handleSelectItem() {
      this.$refs.itemSelect.showFlag = true;
      this.$refs.itemSelect.getList();
    },
    //物料选择弹出框
    onItemSelected(obj) {
      if (obj != undefined && obj != null) {
        obj.autoGenCodeFlag = false
    /*    const newItem = {
          itemId: obj.itemId,
          itemCode: obj.itemCode,
          itemName: obj.itemName,
          specification: obj.specification,
          unitOfMeasure: obj.unitOfMeasure,
          // 多计量单位
          enableMultiUnit : obj.enableMultiUnit,
          storageUnit: obj.storageUnit,
          storageUnitType: obj.storageUnitType,
          storageRatio: obj.storageRatio
        };*/
        if(this.assemblylineList.length == 0){
          const newItem = {
            lineType: 'after_line',
            itemId: obj.itemId,
            itemCode: obj.itemCode,
            itemName: obj.itemName,
            specification: obj.specification,
            unitOfMeasure: obj.unitOfMeasure,
            lineQuantity: null,
            materialPrice: null,
            materialAmount: null,
            productCost: null,
            price: null,
            billAmount: null,
            warehouseId: null,
            warehouseCode: null,
            warehouseName: null,
            locationId: null,
            locationCode: null,
            locationName: null,
            areaId: null,
            areaCode: null,
            areaName: null,
            // 多计量单位
            enableMultiUnit: obj.enableMultiUnit,
            storageUnit: obj.storageUnit,
            storageUnitType: obj.storageUnitType,
            storageRatio: obj.storageRatio,
            storageUnitQuantity: null,

            bomId: null,
            bomName: null,
            bomCode: null,
            drawNumber:obj.drawNumber,
            enableBatchFlag:obj.enableBatchFlag
          };
          this.assemblylineList.push(newItem)
          // 目前要求就填一条数据  因此先注释 检查是否已存在相同itemId的记录
          /*    const exists = this.assemblylineList.some(item => item.itemId === newItem.itemId);

              if (!exists) {
                this.tableData.push(newItem);
                this.$message.success('物品已添加到表格');
              } else {
                this.$message.warning('该物品已存在于表格中');
              }
              */
        }else{
          this.$modal.msgWarning("组装后产品无法增加多条数据");
          return
        }



      }
    },
    async handleLineAutoGenCode(autoGenCodeFlag, row) {
      try {
        if (autoGenCodeFlag) {
          const codedata = await genCode('BATCH_CODE_NEW')
          this.$set(row, 'batchCode', codedata)
        } else {
          this.$set(row, 'batchCode', null)
        }
        // 自动同步开关状态（根据业务需要）
        this.$set(row, 'autoGenCodeFlag', autoGenCodeFlag)
      } catch (error) {
        console.error('生成批次号失败:', error)
        this.$set(row, 'autoGenCodeFlag', !autoGenCodeFlag) // 回滚开关状态
      }
      /*   this.$nextTick(() => {
           this.tableKey++
         })*/
    },
    //修改费用
    handleChangeCost(index,row){
      // 金额 = 材料金额 + 费用
      row.billAmount = (Number(row.materialAmount) + Number(row.productCost)).toFixed(2);

      // 单价 = 金额 / 数量
      if (row.lineQuantity && row.lineQuantity !== 0) {
        row.price = (Number(row.billAmount) / Number(row.lineQuantity)).toFixed(2);
      } else {
        this.$modal.msgWarning("请填写数量");
        return
      }
       this.$forceUpdate();
    },
    handleChangeZhu(index,row){
      if('Y' == row.enableMultiUnit) {

        if (row.storageUnitType === 'fixed') {
          console.log(row)
          // 辅单位数量=主数量 / 换算比例
          row.storageUnitQuantity = parseFloat(
            (row.lineQuantity / row.storageRatio).toFixed(7)
          );
          console.log("ddddddd",row.storageUnitQuantity)
        }
        //浮动换算就得 填写两个数量计算出浮动率就可以了
        if (row.storageUnitType === 'float') {
          if (row.storageUnitQuantity > 0 && row.lineQuantity > 0) {

            // 计算新换算比例 = 主数量 / 库存单位数量
            row.storageRatio = parseFloat(
              (row.lineQuantity / row.storageUnitQuantity).toFixed(4)
            );
          }
        }

      }
    },
    handleChangeFu(index,row){
      if (row.storageUnitType === 'fixed') {
        console.log("fuuuuuuuuuuuuuu")
        console.log("fuuuuuuuuuuuuuu",row)
        // 主数量 = 库存单位数量 * 换算比例
        row.lineQuantity = parseFloat(
          (row.storageUnitQuantity * row.storageRatio).toFixed(7)
        );
      }

      //浮动换算就得 填写两个数量计算出浮动率就可以了
      if (row.storageUnitType === 'float') {
        if (row.storageUnitQuantity > 0 && row.lineQuantity > 0) {

          // 计算新换算比例 = 主数量 / 库存单位数量
          row.storageRatio = parseFloat(
            (row.lineQuantity / row.storageUnitQuantity).toFixed(4)
          );
        }
      }
    },
    //修改的时候
    getLineBom(){
      this.bomList=[]
      getBomList({ancestors: '0',status:'发布',itemId: value.itemId}).then(response =>{
        this.bomList=response.data
        this.bomSelectLoading=false
      })
    },
    handleBomVisibleChange(value,row){
      this.bomSelectLoading=true
      this.bomList=[]
      getBomList({ancestors: '0',status:'发布',itemId: value.itemId}).then(response =>{
        this.bomList=response.data
        this.bomSelectLoading=false
      })

    },
    //选择bom
    handleBomChange(value,row){
      row.bomCode=this.bomList.filter(item => item.bomId === value)[0].bomCode
      row.bomName=this.bomList.filter(item => item.bomId === value)[0].bomName
      // this.handleAutoStock()
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }

        // Only calculate sum for the billAmount column
        if (column.property === 'billAmount') {
          const values = data.map(item => Number(item[column.property]));
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            return !isNaN(value) ? prev + curr : prev;
          }, 0);

          // Format the number if needed
          sums[index] = sums[index].toFixed(2);
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },
    // 获取数量标签的类型
    getQuantityTagType(row) {
      // 数量为0或没有库存显示红色danger
      if ( (!row.lineQuantity || row.lineQuantity === 0)) {
        return 'danger';
      }
      // 库存不足显示
      else if (this.insufficientItems.some(item => item.itemId === row.itemId)) {
        return 'success';
      }
      // 其他情况默认样式
      return '';
    },
    //根据bom 和数量 组装前仓库 自动匹配库存
    handleAutoStock(){
      if(!this.beforsWarehouseIds){
        this.$modal.msgWarning("组装前物料仓库不能为空");
        return
      }

      if(this.assemblylineList[0].itemId){
        if(this.assemblylineList[0].lineQuantity >0 ){
          this.beforeLineList=[]
          this.insufficientItems=[]
          getBomItemStock({bomId:this.assemblylineList[0].bomId,lineQuantity:this.assemblylineList[0].lineQuantity,beforsWarehouseIds:this.beforsWarehouseIds}).then(response => {
            this.beforeLineList = response.data.sufficientItems;
            this.insufficientItems=response.data.insufficientItems

            //累计计算总金额
            const totalBillAmount = this.beforeLineList.reduce((sum, item) => {
              // 确保 billAmount 是数字（如果是字符串，用 parseFloat 转换）
              const amount = typeof item.billAmount === 'number' ? item.billAmount : parseFloat(item.billAmount) || 0;
              return sum + amount;
            }, 0);
            //反写组装后产品 的材料金额  材料单价  材料金额=组装前的所有物料金额总和 材料单价=材料金额/产品数量
            this.assemblylineList[0].materialAmount=totalBillAmount
            this.assemblylineList[0].materialPrice = (totalBillAmount / this.assemblylineList[0].lineQuantity).toFixed(2);
            //组装后产品的 金额=材料金额+费用
            this.assemblylineList[0].billAmount=this.assemblylineList[0].materialAmount+this.assemblylineList[0].productCost
            //组装后产品的 单价(入库的单据)=金额/产品数量
            this.assemblylineList[0].price = (this.assemblylineList[0].billAmount / this.assemblylineList[0].lineQuantity).toFixed(2);

          });
        }else{
          this.$modal.msgWarning("组装后产品数量不能为0");
          return
        }
      } else{
        this.$modal.msgWarning("组装后产品不能为空");
        return
      }

    },
    // 组装后选择仓库  库区 库位
    //获取仓库
    getWarehouse(){
      this.toWarehouseList=[]
      getWarehouseList().then(response => {
        this.toWarehouseList = response.data.filter((el) =>{
          return el.warehouseCode.indexOf('VIR') == -1;
        })
      });
      this.getLocation()
      this.getArea()
    },

    //选择仓库
    handleToWarehouseChange(value,row){
      console.log("cccccccc",value)
      //清空库区 库位
      if(row.locationId){
        this.$set(row, 'lcationId', null)
        this.$set(row, 'locationName', null)
        this.$set(row, 'locationCode', null)
      }
      if(row.areaId){
        this.$set(row, 'areaId', null)
        this.$set(row, 'areaName', null)
        this.$set(row, 'areaCode', null)
      }
      row.warehouseCode=this.toWarehouseList.filter(item => item.warehouseId === value)[0].warehouseCode
      row.warehouseName=this.toWarehouseList.filter(item => item.warehouseId === value)[0].warehouseName
    },
    //选择库区
    handleLocationChange(value,row){
      //清空库位
      if(row.areaId){
        this.$set(row, 'areaId', null)
        this.$set(row, 'areaName', null)
        this.$set(row, 'areaCode', null)
      }

      row.locationName=this.locationList.filter(item => item.locationId === value)[0].locationName
      row.locationCode=this.locationList.filter(item => item.locationId === value)[0].locationCode
      this.$forceUpdate()
      // this.tableKey++;
    },
    //获取库区
    getLocation(warehouseId){
      this.locationList=[]
      if(warehouseId){
        getLocationList({warehouseId:warehouseId}).then(response => {
          this.locationList = response.data;
        });
      }else{
        getLocationList().then(response => {
          this.locationList = response.data;
        });
      }
    },
    //获取库位
    getArea(locationId){
      this.areaList=[]
      if(locationId){
        getAreaList({locationId:locationId}).then(response => {
          this.areaList = response.data;
        });
      }else{
        getAreaList().then(response => {
          this.areaList = response.data;
        });
      }
    },
    //下拉的时候加载仓库下的库区
    handleToLocationVisibleChange(value,row){
      this.locationSelectLoading=true
      if (value) {
        //加载仓库下的库区
        this.getLocation(value.warehouseId)
        this.locationSelectLoading=false
        // 在这里执行打开下拉框时的操作
      } else {
        console.log('下拉框关闭了');
        // 在这里执行关闭下拉框时的操作
      }
    },
    //下拉的时候加载库区下的库位
    handleVisibleChange(value,row){
      this.areaSelectLoading=true
      if (value) {
        this.getArea(value.locationId)
        this.areaSelectLoading=false
        console.log("qqqqqqqqqq",value)
        // 在这里执行打开下拉框时的操作
      } else {
        console.log('下拉框关闭了');
        // 在这里执行关闭下拉框时的操作
      }

    },
    //选择库位
    handleAreaChange(value,row){
      console.log("11111111111111",row)
      this.$set(row, 'areaName', this.areaList.filter(item => item.areaId === value)[0].areaName)
      this.$set(row, 'areaCode', this.areaList.filter(item => item.areaId === value)[0].areaCode)
      this.$forceUpdate()
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lineId: null,assemblyId:null,  lineType:null,      itemId: null,        itemCode: null,        itemName: null,        specification: null,
        unitOfMeasure: null,        lineQuantity: null,        materialPrice: null,        materialAmount: null,
        productCost: null,        price: null,        billAmount: null,        warehouseId: null,        warehouseCode: null,
        warehouseName: null,        locationId: null,        locationCode: null,        locationName: null,        areaId: null,
        areaCode: null,        areaName: null,        storageUnit: null,        storageUnitType: null,        storageRatio: null,
        storageUnitQuantity: null,        enableMultiUnit: null,        bomId: null,  bomCode:null,      bomName: null,        createBy: null,
        createByName: null,        createTime: null,        updateTime: null,        updateBy: null   ,drawNumber:null  };

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lineId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加组装单行";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lineId = row.lineId || this.ids
      getAssemblyline(lineId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改组装单行";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.lineId != null) {
            updateAssemblyline(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAssemblyline(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row, index) {
     /* const lineIds = row.lineId || this.ids;
      this.$modal.confirm('是否确认删除组装单行编号为"' + lineIds + '"的数据项？').then(function() {
        return delAssemblyline(lineIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});*/

        // 直接通过索引删除（最可靠，不依赖 ID）
        this.assemblylineList.splice(index, 1);
        this.$message.success("删除成功");

    },
    /** 删除按钮操作组装前 */
    handleDeleteBeforeLine(row, index) {
      // 直接通过索引删除（最可靠，不依赖 ID）
      this.beforeLineList.splice(index, 1);

      //累计计算总金额
      const totalBillAmount = this.beforeLineList.reduce((sum, item) => {
        // 确保 billAmount 是数字（如果是字符串，用 parseFloat 转换）
        const amount = typeof item.billAmount === 'number' ? item.billAmount : parseFloat(item.billAmount) || 0;
        return sum + amount;
      }, 0);
      //反写组装后产品 的材料金额  材料单价  材料金额=组装前的所有物料金额总和 材料单价=材料金额/产品数量
      this.assemblylineList[0].materialAmount=totalBillAmount
      this.assemblylineList[0].materialPrice = (totalBillAmount / this.assemblylineList[0].lineQuantity).toFixed(2);
      //组装后产品的 金额=材料金额+费用
      this.assemblylineList[0].billAmount=this.assemblylineList[0].materialAmount+this.assemblylineList[0].productCost
      //组装后产品的 单价(入库的单据)=金额/产品数量
      this.assemblylineList[0].price = (this.assemblylineList[0].billAmount / this.assemblylineList[0].lineQuantity).toFixed(2);


      this.$message.success("删除成功");

    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('wm/assemblyline/export', {
        ...this.queryParams
      }, `assemblyline_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

